<script lang="ts" setup>
import { ModernAuthenticationLogin } from '@vben/common-ui';
import { ModernAuthLayout } from '@vben/layouts';

import { message } from 'ant-design-vue';

import { sendSmsCodeApi } from '#/api';
import { useAuthStore } from '#/store';

defineOptions({ name: 'Login' });

const authStore = useAuthStore();

// 发送验证码（登录模式）
async function handleSendCode(mobile: string) {
  try {
    await sendSmsCodeApi({
      mobile,
      smsmode: 2, // 2-登录模式
    });
    message.success('验证码已发送到您的手机');
  } catch (error: any) {
    message.error(error.message || '发送验证码失败，请重试');
    throw error; // 重新抛出错误，阻止倒计时
  }
}

// 处理登录提交
async function handleSubmit(formData: any) {
  // 判断是手机登录还是账号登录
  if (formData.mobile && formData.code) {
    // 手机号登录 - 使用真实API
    try {
      await authStore.authPhoneLogin({
        mobile: formData.mobile,
        code: formData.code,
      });
    } catch (error: any) {
      message.error(error.message || '登录失败，请检查手机号和验证码');
    }
  } else {
    // 账号密码登录
    await authStore.authLogin({
      ...formData,
      captcha: '',
      checkKey: '',
    });
  }
}
</script>

<template>
  <ModernAuthLayout
    app-name="工作平台"
    page-title="欢迎使用工作平台"
    page-description="高效、安全、便捷的工作管理解决方案"
  >
    <ModernAuthenticationLogin
      :loading="authStore.loginLoading"
      :on-send-code="handleSendCode"
      @submit="handleSubmit"
    />
  </ModernAuthLayout>
</template>
